package com.example.easyscript.common.page;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
public class Page<T> implements Serializable {

    private static final long serialVersionUID = 6645996863226528798L;

    // page size default 100
    @ApiModelProperty(value = "每页数量", example = "100")
    protected long size = 100;
    // current index default 0
    @ApiModelProperty(value = "当前页", example = "1")
    protected long current = 1;
    @ApiModelProperty(value = "0-分页1-不分页", hidden = true)
    protected int isPage = 0;
    @ApiModelProperty(value = "偏移量", hidden = true)
    protected long offset = 0;

    // limit start position
    public long offset() {
        long current = this.getCurrent();
        long offset = current <= 1L ? 0L : Math.max((current - 1L) * this.getSize(), 0L);
        this.setOffset(offset);
        return current <= 1L ? 0L : Math.max((current - 1L) * this.getSize(), 0L);
    }

    @ApiModelProperty("结果集")
    protected T records;
    @ApiModelProperty("总条数")
    protected long total = 0;
    @ApiModelProperty("总页数")
    protected long pages = 0;
    @ApiModelProperty("扩展数据")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected T extra;
    @ApiModelProperty("表头信息")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected T head;

    public void setTotal(long total) {
        this.total = total;
        if (this.getSize() == 0L) {
            this.pages = 0L;
        } else {
            long pages = this.getTotal() / this.getSize();
            if (this.getTotal() % this.getSize() != 0L) {
                ++pages;
            }
            this.pages = pages;
        }
    }

}
